package com.itheima.controller;


import com.itheima.common.R;
import com.itheima.entity.User;
import com.itheima.entity.UserDto;
import com.itheima.service.UserService;
import com.itheima.utils.AliyunSmsUtil;
import com.itheima.utils.ValidateCodeUtils;

import com.sun.org.apache.bcel.internal.classfile.Code;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;


    @PostMapping("/sendMsg")
    public R<UserDto> sendMsg(HttpServletRequest request, @RequestBody User user) {
        //获取用户手机号
        String phone = user.getPhone();
        //生成随机6位验证码
        Integer code = ValidateCodeUtils.generateValidateCode(6);
        //调用阿里云提供的短信服务api完成发送短信
//        AliyunSmsUtil.sendSms(phone, cod/**/e);

        //需要将验证码保存到Session
        HttpSession session = request.getSession();
        session.setAttribute("code", code.toString());
        System.out.println("验证码: " + code);
        UserDto userDto = new UserDto();
        userDto.setPhone(phone);
        userDto.setCode(code);
        return R.success(userDto);
    }

    @PostMapping("/login")
    public R<String> login(HttpServletRequest request, @RequestBody UserDto userDto) {

        //Session取验证码
        HttpSession session = request.getSession();
        //获取session里面的code的值
        Object code = session.getAttribute("code");
        Integer code1 = userDto.getCode();
        if (code.equals(String.valueOf(code1))) {
            //验证码正确
            return R.success("验证成功");
        } else {
            //验证码错误
            return R.error("验证码错误");
        }
    }
}
